import React from 'react';
import { Radio, Button } from 'antd';
import { isEqual } from 'lodash';

import { Action, Config, JsonGroup } from '../../types';
import { setCondition, setNot } from '../../store/actions';

const RuleGroupConditions: React.FC<{
  config: Config,
  not: boolean,
  condition: JsonGroup["condition"],
  path: string,
  onChange: (action: Action) => void,
}> = React.memo((props) => {
  const { config, not, condition, path, onChange } = props;

  return (
    <Radio.Group
      style={{pointerEvents: config.settings.readonly ? 'none' : 'auto'}}
      value={condition}
      onChange={(e) => onChange(setCondition(e.target.value, path||""))}
      buttonStyle="solid"
      size={config.settings.size}
    >
      {config.settings.showNot && (
        <Button
          disabled={config.settings.readonly}
          size={config.settings.size}
          type={not ? "primary" : "default" }
          onClick={() => onChange(setNot(!not, path||""))}
        >
          NOT
        </Button>
      )}
      {config.settings.showCondition && Object.keys(config.conditions).map(condition => (
        <Radio.Button
          key={condition}
          value={config.conditions[condition].label}
        >
          {config.conditions[condition].label}
        </Radio.Button>
      ))}
    </Radio.Group>
  );
}, (prevProps, nextProps) => {
  if (isEqual(nextProps.config, prevProps.config)) {
    if (!isEqual(nextProps.condition, prevProps.condition)) {
      return false;
    }
    if (!isEqual(nextProps.not, prevProps.not)) {
      return false;
    }
    return true;
  } else {
    return false;
  }
});

export default RuleGroupConditions;
